import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:wanandroid/splash_screen.dart';
import 'package:wanandroid/util/theme_util.dart';
import 'package:wanandroid/util/utils.dart';

import 'app.dart';
import 'common/application.dart';
import 'common/logger.dart';
import 'common/user_info_model.dart';
import 'event/change_theme_event.dart';
import 'loading.dart';
import 'dart:io';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  getLoginInfo();
  runApp(const MyApp());
  if (Platform.isAndroid) {
    // 以下两行 设置android状态栏为透明的沉浸。写在组件渲染之后，是为了在渲染后进行set赋值，覆盖状态栏，写在渲染之前MaterialApp组件会覆盖掉这个值。
    SystemUiOverlayStyle systemUiOverlayStyle =
    const SystemUiOverlayStyle(statusBarColor: Colors.transparent);
    SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
  }
}

Future<Null> getLoginInfo() async {
  User().getUserInfo();
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<StatefulWidget> createState() {
    return MyAppState();
  }
}

class MyAppState extends State<MyApp> {

  Color themeColor = ThemeUtils.currentColorTheme;

  @override
  void initState() {
    super.initState();
    Utils.getColorThemeIndex().then((index) {
      logger.d('color theme index = $index');
      if (index != null) {
        ThemeUtils.currentColorTheme = ThemeUtils.supportColors[index];
        Application.eventBus.fire(ChangeThemeEvent(ThemeUtils.supportColors[index]));
      }
    });

    Application.eventBus.on<ChangeThemeEvent>().listen((event) {
      setState(() {
        themeColor = event.color ?? Colors.black;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "玩Android",
      debugShowCheckedModeBanner: false,
      theme: ThemeData(primaryColor: themeColor, brightness: Brightness.light),
      routes: <String, WidgetBuilder>{
        "app": (BuildContext context) => const App(),
        "splash": (BuildContext context) => const SplashScreen(),
      },
      home: const LoadingPage(),
    );
  }
}
